<?php
/**
 * Created by PhpStorm.
 * User: acker
 * Date: 21-06-08
 * Time: 下午6:25
 */

namespace App\Models\yb;
use App\Models\AdminUserModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use EasyWeChat\Factory;


class GoodsOrderModel extends Model
{
    use DefaultDatetimeFormat;

    use SoftDeletes;

    /**
     *
     *计量单位
     * @var string
     */
    protected $table = 'yb_goods_order';

    /**
     * 主键
     *
     * @var string
     */
    protected $primaryKey = 'id';



    /**
     * 该模型是否被自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = true;


    /**
     * 主键
     *
     * @var string
     */
    protected $appends = ['action_id'];

    /**
     * @return mixed
     */
    public function getActionIdAttribute(){
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function Goods()
    {
        return $this->hasOne(GoodsModel::class,'id','goods_id');
    }

    /**
     * @return mixed
     */
    public function User()
    {
        return $this->hasOne(UserModel::class,'id','user_id');
    }

    /**
     * @return mixed
     */
    public function Network()
    {
        return $this->hasOne(AdminUserModel::class,'id','network_id');
    }


    public static function getConfig()
    {
        return [
            // 必要配置
            'app_id' =>  env('WECHAT_APP_ID'),
            'mch_id' => env('WECHAT_MCH_ID'),
            'key' =>  env('WECHAT_KEY'),   // API 密钥
        ];
    }

    public static function payByWeChat($orderSn, $openid, $amount)
    {

        $payment = Factory::payment(self::getConfig());

        $jssdk = $payment->jssdk;

        $result = $payment->order->unify([
            'body' => env('APP_NAME'),         // 订单说明
            'out_trade_no' => $orderSn,   // 平台内部订单号
            'total_fee' => $amount * 100,   // 价格, 单位为分
            'notify_url' => env('APP_URL').'api/order/goods/notify_url', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id'];

            $config = $jssdk->sdkConfig($prepayId);

            return $config;
        }

        if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
            throw new \Exception($result['return_msg']);
        }

        throw new \Exception($result['err_code_des']);
    }

        /**
     * Get a JWT via given credentials.
     *  推送
     * @return \Illuminate\Http\JsonResponse
     */
    public static function orderPush($openid,$orderSn)
    {

        $config = [
            'app_id' => 'wx3cfd9698645432e9',
            'secret' => '0b5b897aa5751aa1e414ce1a15d6d6d5',
            'token' => 'C1089F8BE36698A4EB575EDBB5919B60',
            'response_type' => 'array',
            'aes_key' => '461wQLRvxu4j7nGfm0FASGHFpTY1lm2JfJyWgzqWTgP'
        ];

        $app = Factory::officialAccount($config);

        $app->template_message->send([
            'touser' => $openid,
            'template_id' => 'WGbDbd6L19-dgwoF9VVFRcvl3VVpdMs87d5_yEY-gtQ',
            'miniprogram' => [
                    'appid' => 'wx2daad6e45cc01181',
                    'page' => 'pages/index/index',
            ],
            'data' => [
                'first' => '您有新订单创建，请迅速响应。',
                'keyword1' => '待接单',
                'keyword2' => $orderSn,
                'keyword3' => date('Y-m-d H:i:s',time()),
                'remark' => '订单全部信息请点击“详情”进行查看'
            ],
        ]);
    }



}
